import React, { useState, useEffect } from "react";
import Taro from "@tarojs/taro";
import { getCurrentInstance } from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtCheckbox } from "taro-ui";

import api from "@api/api.js";
import "./index.less";

export default (props) => {
  const [id, setId] = useState({}); // 上级页面参数
  const [list, setList] = useState([]); //手术列表
  const [selecList, setSelectList] = useState([]); //选中的手术
  const [types, setType] = useState("");
  useEffect(() => {
    // 判断是案例还是方案
    const type = getCurrentInstance().router.params.type;
    const id = getCurrentInstance().router.params.id;
    if (type == "case") {
      setType("case");
      getSurgicalList(id, type);
    } else {
      setId(id);
      getSurgicalList(id);
    }
  }, []);

  // 选择的手术
  const change = (value) => {
    setSelectList(value);
  };

  // 获取手术列表
  const getSurgicalList = async (id, type) => {
    const { data } = await (type
      ? api.getOperation({ id: id })
      : api.getSurgical(id));
    if (data) {
      const arr = [];
      const selectArr = [];
      data.map((item) => {
        const res = {
          value: type ? item.id : item.optionId,
          label: type ? item.name : item.optionName,
        };
        arr.push(res);
        if (item.checked) {
          selectArr.push(res.value);
        }
      });
      setList(arr);
      setSelectList(selectArr);
    }
  };

  // 下一步
  const save = async () => {
    if (types == "case") {
      Taro.navigateTo({
        url: `/pages/select-material/index?id=${JSON.stringify(
          selecList
        )}&type=case`,
      });
    } else {
      const {
        data: { clinicSchemesId },
      } = await api.saveSurgicalList({ surgicalIds: selecList }, id);
      Taro.navigateTo({
        url: `/pages/select-material/index?id=${clinicSchemesId}`,
      });
    }
  };
  return (
    <View className="bgBox">
      <View className="listBox myRadio">
        <AtCheckbox
          options={list}
          selectedList={selecList}
          onChange={change.bind(this)}
        />
      </View>
      <View className="bottomBtn" onClick={save}>
        <View>下一步</View>
      </View>
    </View>
  );
};
